<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { getWXFastApi } from '@/services/login'
import {
  useLoginStore,
  useMemberStore,
  useLocationStore,
  usePhoneStore,
  useDeviceStore,
} from '@/stores'
import type { userInfo } from '@/types/component'
import useCurrentPages from '@/hooks/useCurrentPages'

const { getCurrentPagesFn, pages } = useCurrentPages()
const phoneStore = usePhoneStore()
const props = defineProps<{
  invitationClientId?: string
  enterprise?: number
}>()
const memberStore = useMemberStore() // 本地缓存
const loginStore = useLoginStore()
const locationStore = useLocationStore()
const deviceStore = useDeviceStore()

/**
 * *  popupRef 导出弹窗方法
 */
const popupRef = ref<{
  open: () => void
  close: () => void
}>()
const open = () => {
  popupRef.value?.open()
}
const close = () => {
  popupRef.value?.close()
}
defineExpose({
  open,
  close,
})
// 确认用户协议
let classIcon = ref('icon-ring')

const isButton = computed(() => {
  if (classIcon.value === 'icon-ring') {
    return 0
  } else if (classIcon.value === 'icon-checked' && loginStore.isLogin?.isType) {
    return 1
  } else if (classIcon.value === 'icon-checked' && !loginStore.isLogin?.isType) {
    return 2
  }
})
/**
 * * iconSwiper 触发用户协议
 */
const iconSwiper = () => {
  if (classIcon.value === 'icon-ring') {
    classIcon.value = 'icon-checked'
  } else {
    classIcon.value = 'icon-ring'
  }
}

// 组件每次调用的时候触发方法和参数
onMounted(() => {
  getCurrentPagesFn()
  fullPath.value = pages.value[pages.value.length - 1].$page.fullPath
})
let fullPath = ref()
/**
 * *   手机号跳转
 */
const phoneLoginFn = () => {
  // 用户协议
  if (classIcon.value === 'icon-ring') {
    return uni.showToast({
      title: '请先阅读并勾选协议',
      icon: 'none',
    })
  }
  popupRef.value?.close() // 关掉弹出层
  uni.navigateTo({
    url: `/pages/login/login?openId=${loginStore.isLogin?.openId}&unionId=${loginStore.isLogin?.unionId}&invitationClientId=${props.invitationClientId}&enterprise=${props.enterprise}`,
  })
}

let loading = ref(false)

import { isUserOneLoginApi } from '@/services/login'
import { PageSkip, Toast } from '@/utils/tools'
import { getBalanceApi, getHasPayPasswordApi, getPayPasswordFreeApi } from '@/services/wallet'

/** 调用自己的登录接口 */
const getMyLogin = () => {
  uni.login({
    success: async (success: UniApp.LoginRes) => {
      // console.log('weChatCode', success.code, 'invitationClientId', props.invitationClientId)
      const res = await isUserOneLoginApi({
        weChatCode: success.code, // success.code
        invitationClientId: props.invitationClientId,
        enterprise: props.enterprise,
        cityName: locationStore.location?.cityName,
      })
      if (res.code === 200) {
        // console.log('isUserOneLoginApi', res)
        updateUserInformation(res.data)
        getBalance()
        getPayPasswordFree()
        getHasPayPassword()
        popupRef.value?.close() // 关闭弹出层
        onSkipPgae()
        emits('refreshFoodList')
      } else if (res.code === 205) {
        console.log('205', res)
        loginStore.isLogin!.isType = false
      }
    },
  })
}
/**
 * * 请求成功后更新用户信息
 */
const updateUserInformation = (data: any) => {
  memberStore.setToken(data.accessToken)
  let user = <userInfo>{
    unionId: data.client.unionId,
    headImg: data.client.headImg,
    nickName: data.client.nickName,
    id: data.client.id,
    birthday: data.client.birthday,
    sex: data.client.sex,
    openId: data.client.openId,
    mobile: data.client.mobile,
    email: data.client.email,
  }
  loginStore.isLogin!.isType = true
  memberStore.setUserInfo(user)
}

// 获取用户钱包余额
const getBalance = async () => {
  const res = await getBalanceApi()
  if (res.code === 200) {
    memberStore.setBalanceInfo(res.data)
  }
}

// 是否开启免密支付
async function getPayPasswordFree() {
  const res = await getPayPasswordFreeApi()
  if (res.code === 200) {
    memberStore.setHasPayPasswordFree(res?.data)
  }
}

// 获取用户是否存在支付密码
const getHasPayPassword = async () => {
  const res = await getHasPayPasswordApi()
  if (res.code === 200) {
    memberStore.setHasPayPassword(res.data)
  }
}
/**
 * * 调用快速登录组件
 */
const getPhoneNumberFn = async (ev: any) => {
  loading.value = true
  // console.log(ev)
  const WXFastParm = {
    openId: loginStore.isLogin!.openId,
    unionId: loginStore.isLogin!.unionId,
    weChatCode: ev.detail.code,
    invitationClientId: props.invitationClientId,
    enterprise: props.enterprise,
    cityName: locationStore.location?.cityName,
  }
  // console.log('WXFastParm', WXFastParm)
  try {
    const res = await getWXFastApi(WXFastParm)
    console.log('getWXFastApi', res)
    loading.value = false
    updateUserInformation(res.data)
    getBalance()
    getHasPayPassword()
    getPayPasswordFree()
    popupRef.value?.close() // 关闭弹出层
    onSkipPgae()
    emits('refreshFoodList')
  } finally {
    loading.value = false
  }
}

/**跳转到之前页面 */
const onSkipPgae = () => {
  console.log('fullPath', fullPath.value)
  if (fullPath.value.startsWith('/pages/eat/eat')) {
    PageSkip(`${fullPath.value}?machineId=${deviceStore?.deviceInfo?.machineId}`, 'reLaunch')
    return
  }

  const pageList = ['/pages/index/index', '/pages/goods/goods', '/pages/my/my']
  const isSkipType = pageList.some((item) => fullPath.value.startsWith(item))

  isSkipType ? PageSkip(fullPath.value, 'reLaunch') : PageSkip(fullPath.value)
}
const emits = defineEmits<{
  (event: 'refreshFoodList'): void
}>()
</script>

<template>
  <uni-popup ref="popupRef" type="bottom" :safe-area="false">
    <!-- 弹出层 -->
    <view class="popup_view">
      <uni-icons
        class="uni_icons"
        type="closeempty"
        size="25"
        @tap="popupRef?.close(), (loading = false)"
      ></uni-icons>
      <view class="view_image">
        <image src="/static/images/logo_.png" mode="scaleToFill" />
      </view>
      <!-- 占位模块 -->
      <view class="view_image_1"></view>
      <view class="view_text">开始享受您的美味时刻</view>
      <view class="view_text_two">立即登录，解锁更多您的专属优惠</view>
      <view class="userAgreement">
        <view @tap="iconSwiper" class="text">
          <view class="iconfont" :class="classIcon"></view>已阅读并同意麦德范
        </view>
        <navigator hover-class="none" url="/pagesMy/userAgreement/userAgreement" class="text_one"
          >《用户协议》</navigator
        >
        <!-- &laquo; &raquo; -->
        <navigator hover-class="none" url="/pagesMy/userAgreement/PrivacyPolicy" class="text_two"
          >《隐私政策》</navigator
        >
      </view>
      <button
        v-if="isButton === 0"
        hover-class="view-hover"
        class="quickLogin"
        @tap="Toast('请先阅读并勾选协议')"
      >
        一键登录
      </button>

      <button
        v-else-if="isButton === 1"
        class="quickLogin"
        hover-class="view-hover"
        :loading="loading"
        :disabled="loading"
        @tap="getMyLogin()"
      >
        一键登录
      </button>
      <button
        v-else-if="isButton === 2"
        class="quickLogin"
        hover-class="view-hover"
        :loading="loading"
        :disabled="loading"
        open-type="getPhoneNumber"
        @getphonenumber="getPhoneNumberFn"
      >
        一键登录
      </button>

      <!-- <view class="phoneLogin" @tap="phoneLoginFn">
        <text class="iconfont icon_Frame-4"></text>手机验证码登录
      </view> -->
    </view>
  </uni-popup>
</template>

<style lang="scss">
.popup_view {
  position: relative;
  width: 100%;
  height: 680rpx;
  padding: 0 36rpx;
  border-radius: 32rpx 32rpx 0 0;
  background-color: #fff;
  z-index: 999;
  .uni_icons {
    position: absolute;
    top: 40rpx;
    right: 36rpx;
  }
  .view_image {
    position: absolute;
    display: flex;
    justify-content: flex-start;
    top: 64rpx;
    width: 194rpx;
    height: 60rpx;
  }
  //占位模块
  .view_image_1 {
    width: 100%;
    height: 114rpx;
  }
  .view_text {
    margin-top: 90rpx;
    width: 380rpx;
    height: 54rpx;
    line-height: 54rpx;
    font-size: 38rpx;
  }
  .view_text_two {
    margin-top: 12rpx;
    width: 330rpx;
    height: 30rpx;
    font-size: 22rpx;
    color: #00000080;
  }
  .userAgreement {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 70rpx;
    font-size: 22rpx;
    width: 546rpx;
    color: #00000080;
    .text {
      display: flex;
      justify-content: center;
      align-items: center;
      .iconfont {
        margin-right: 10rpx;
        font-size: 28rpx;
      }
      .icon-checked {
        color: $uni-color-motif;
      }
    }
    .text_one,
    .text_two {
      color: $uni-color-motif;
    }
  }
  .quickLogin {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 26rpx 0 36rpx 0;
    border-radius: 44rpx;
    width: 100%;
    height: 88rpx;
    font-size: 30rpx;
    background-color: $uni-color-motif;
    color: #fff;
  }
  .phoneLogin {
    display: flex;
    margin: 0 auto;
    align-items: center;
    width: 198rpx;
    height: 52rpx;
    font-size: 22rpx;
    color: #00000080;
    .iconfont {
      font-size: 32rpx;
      margin-right: 10rpx;
    }
  }
}
</style>
